/*
 * tournament.cpp
 *
 *  Created on: 25/02/2012
 *      Author: Manuel Cortés / Juan Castellanos
 */
 
#include "tournament.h"

tournament::tournament( void )
{
	competitors = new team[2];
	number_competitors = 2;
	cout << "The teams are: " << getNumberCompetitors( ) << endl;
}

tournament::tournament( team *competitors, int number_competitors )
{
	if( ( number_competitors & 1 ) || ( number_competitors == 0 ) ){
		cout << "Even numbers only " << endl;
	}else{
		this->competitors = competitors;
		this->number_competitors = number_competitors;
		cout << "The teams are: " << number_competitors << endl;	
	}
}

tournament::~tournament( void )
{
	cout << " GAME OVER" << endl;
	//~ delete [] competitors;
}

void tournament::setCompetitors( team *competitors )
{
	this->competitors = competitors;	
}

team* tournament::getCompetitors( void )
{
	return competitors;
}

int tournament::getNumberCompetitors( void )
{
	return number_competitors;
}

void tournament::doubleRoundRobin( void )
{
	int total_rounds = 2*(number_competitors - 1);
	int rounds = number_competitors - 1;
	int games = number_competitors / 2;
	int temp1;
	int temp2;
	int flag1 = HOME;
	int flag2 = AWAY;
	
	for( int i = 0; i < total_rounds; i++ ){
		cout << "Jornada " << i+1 << endl;
		flag1 = i & 1;
		flag2 = ~( i & 1 );
		if( flag1 == HOME ){
			cout << "HOME       AWAY" << endl;
		}else{
			cout << "AWAY       HOME" << endl;
		}
		if( i < rounds ){
			temp2 = rounds - i;			
		}else{
			temp2 = 2*rounds - i;				
		}
		cout << competitors[0].getID( ) << "\tvs\t" << competitors[temp2].getID( ) << endl;		
		temp1 = temp2;
		for( int j = 1; j < games; j++ ){
			if( ( temp2 == rounds ) && ( j == 1 ) ){ 
				temp1 = 0;
			}
			if( temp1 == rounds ){;
				temp1 = 0;
			}
			if( temp2 == 1 ){
				temp2 = rounds + 1;
			}
			temp1++;
			temp2--;
			cout << competitors[ temp1 ].getID( ) << "\tvs\t" << competitors[ temp2 ].getID( ) << endl;
		}	
		cout << endl;
	}
}

void tournament::print( void )
{
	team *temp1 = getCompetitors();
	cout << " Torneo 2012 " << endl;
	cout << " Actualmente estan inscritos " << getNumberCompetitors() << endl;
	cout << " Los equipos son: " << endl;
	for( int i = 0; i < getNumberCompetitors(); i++ ){
		cout << temp1[i].getName() << endl;
	}
}

int tournament::readFile( team *competitors, string filePath )
{
	int i = 0;
	ifstream ifs;
	string line;
	ifs.open( filePath.c_str() );
	
	if( ifs.is_open() ){
		ifs >> line;
		while( !ifs.eof() )
		{
			ifs >> line;
			competitors[i].setID( i );
			competitors[i].setName( line );
			i++;		
		}
		ifs.close( );
		return 0;		
	}else{
		cout << "ERROR: File not found or it can be readed." << endl;
		return -1;
	}
}
